package com.bto.solar.work.service;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.bto.solar.work.common.BizException;
import com.bto.solar.work.common.R;
import com.bto.solar.work.constant.BizCode;
import com.bto.solar.work.constant.DBConstants;
import com.bto.solar.work.dao.ICompanyService;
import com.bto.solar.work.dao.IDepartmentService;
import com.bto.solar.work.dao.IUserService;
import com.bto.solar.work.dto.CompanyRes;
import com.bto.solar.work.dto.DepartmentRes;
import com.bto.solar.work.entity.Company;
import com.bto.solar.work.entity.Department;
import com.bto.solar.work.entity.User;
import com.bto.solar.work.utils.DepartmentUtils;
import com.bto.solar.work.utils.NullUtils;
import com.bto.solar.work.utils.StringUtils;
import com.bto.solar.work.utils.tree.TreeUtils;
import com.bto.solar.work.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shiyi
 */
@Slf4j
@Service
public class BtoDepartmentService {

    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    @Lazy
    private BtoUserService btoUserService;

    @Autowired
    private IUserService userService;

    /**
    * 查询部门管理页面
    * */
    public JSONArray getAllOrg(){
        List<Department> departments = departmentService.list();
        ArrayList<DepartmentRes> departmentResArrayList = new ArrayList<>();
        for (Department department : departments) {
            DepartmentRes departmentRes = DepartmentUtils.copyDepartmentRes(department);
            departmentResArrayList.add(departmentRes);
        }
        ArrayList<DepartmentRes> list = new ArrayList<>();
        HashMap<String, DepartmentRes> map = new HashMap<>();
        //把所有部门转化成map结构，key为组织编码，value为组织对象
        for (DepartmentRes department : departmentResArrayList) {
            if (StringUtils.isNotEmpty(department.getDepartmentId().toString())){
                map.put(department.getDepartmentId().toString() , department);
            }
        }
        //实现树形结构
        for (DepartmentRes department : departmentResArrayList) {
            //获取父级id
            String code = department.getParentId().toString();
            DepartmentRes parent = map.get(code);
            //根据最高级组织中parentCode为0或者以parentCode为组织编码查不到组织的原理，把最高级组织对象add到list结构中
            if (department.getParentId() == 0){
                list.add(department);
            }else {
                Collection<DepartmentRes> children = parent.getDepartmentRes();
                if (CollectionUtils.isEmpty(children)){  //不为空
                    parent.setDepartmentRes(new ArrayList<>());
                }
                parent.getDepartmentRes().add(department);
            }
        }
        //创建map来存放公司id，和部门集合
        Map<Long, List<DepartmentRes>> Map = new HashMap<>();
        Map = list.stream().collect(Collectors.groupingBy(DepartmentRes::getCompanyId));
        List<Company> companies = companyService.list();
        ArrayList<CompanyRes> companyRes = new ArrayList<>();

        Map<Long, List<DepartmentRes>> finalMap = Map;
        companies.stream().forEach(company -> {
            Long companyId = company.getCompanyId();
            CompanyRes res = DepartmentUtils.copyCompanyRes(company);
            res.setDepartments(finalMap.get(companyId));
            companyRes.add(res);
        });

        JSONArray jsonArray = new JSONArray();
        for (CompanyRes department : companyRes) {
            jsonArray.add(department);
        }
        return jsonArray;
    }

    /**
     * 部门新增
     * */
    public R<String> addDepartment(Department department){
        if (department.getDepartmentId() != null){
            throw new BizException(BizCode.BizCommonExceptionCode);
        }
        Company company = companyService.getById(department.getCompanyId());
        if (company == null){
            throw new BizException(BizCode.NOT_HAVE_COMPANY_ERROR);
        }
        if (NullUtils.isNotNull(department.getParentId())) {
            Department departmentById = departmentService.getById(department.getParentId());
            if (departmentById == null){
                throw new BizException("上极部门不存在！");
            }
        } else {
            department.setParentId(0L);
        }
        boolean save = departmentService.save(department);
        if (save) {
            return R.ok("部门新增成功");
        }else {
            return R.ok("部门新增成功");
        }
    }

    /**
     * 部门修改
     * */
    public R<String> updateDepartment(Department department , Integer id){
        Date date = new Date(System.currentTimeMillis());
        long time = date.getTime();
        LambdaQueryWrapper<Department> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Department::getDepartmentId , id);
        Department departmentServiceById = departmentService.getById(id);
        if (departmentServiceById == null){
            throw new BizException(BizCode.NOT_HAVE_ROLE_ERROR);
        }
        department.setUpdateTime(new Timestamp(time));
        boolean update = departmentService.update(department, wrapper);
        if (update) {
            return R.ok("部门修改成功");
        }else {
            return R.fail("部门修改异常");
        }
    }

    /**
     * 部门删除
     * */
    public R<String> deleteDepartment(Integer id){
        LambdaQueryWrapper<Department> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Department::getDepartmentId , id);
        Department departmentServiceById = departmentService.getById(id);
        if (departmentServiceById == null){
            throw new BizException(BizCode.SON_HAVE_ERROR);
        }
        Long parentId = departmentServiceById.getParentId();
        LambdaQueryWrapper<Department> departmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //departmentLambdaQueryWrapper.eq(Department::getDepartmentId , parentId);//查询是否有子节点
        departmentLambdaQueryWrapper.eq(Department::getParentId , id);
        List<Department> list = departmentService.list(departmentLambdaQueryWrapper);
        if (list.isEmpty()){
            if (departmentServiceById == null){
                throw new BizException(BizCode.NOT_HAVE_ROLE_ERROR);
            }
            boolean removeById = departmentService.removeById(id);
            if (removeById) {
                return R.ok("部门删除成功");
            }else {
                return R.fail("部门删除异常");
            }
        }else {
            throw new BizException(BizCode.SON_HAVE_ERROR);
        }

    }


//    /**
//     * 通过userId获取用户部门列表
//     */
//    public List<Department> getDepartmentListByUserId (Long userId) {
//        //获取用户信息
//        User user = btoUserService.getUserByUserId(userId);
//        //判断用户是否存在
//        if (user == null) {
//            throw new BizException(BizCode.USER_ABSENT_ERROR);
//        }
//        return getDepartmentListByUser(user);
//    }
//
//    /**
//     *通过user获取用户部门列表
//     */
//    public List<Department> getDepartmentListByUser (User user) {
//        List<Long> departmentIds = JsonToListUtils.convertJSONArrayToList(user.getDepartmentIds());
//        return departmentService.lambdaQuery().in(Department::getDepartmentId, departmentIds).list();
//    }

    /**
     * 通过 公司ID 获取部门列表
     */
    public List<UserVO.Department> getDepartmentListByCompanyId (Long companyId) {
        User loginUser = btoUserService.getCurrentUser();
        if (null == loginUser) {
            throw new BizException(BizCode.USER_ABSENT_ERROR);
        }
        //不是超级管理员，且不是公司管理员，则只能获取到本公司的部门列表
        if (!btoUserService.isUserSuperAdmin(loginUser) && !btoUserService.isUserBelongHeadCompany(loginUser)) {
            companyId = loginUser.getCompanyId();
        }
        List<UserVO.Department> userDepartmentList = departmentService.lambdaQuery()
                .eq(Department::getCompanyId, companyId).list().stream()
                .map(department -> {
                    UserVO.Department departmentVO = new UserVO.Department();
                    departmentVO.setDepartmentId(department.getDepartmentId())
                            .setName(department.getName())
                            .setParentId(department.getParentId());
                    return departmentVO;
                }).collect(Collectors.toList());
        Map<String, UserVO.Department> userDepartmentMap = userDepartmentList.stream()
                .collect(Collectors.toMap(userDepartment -> userDepartment.getDepartmentId().toString() , userDepartment -> userDepartment));
        return TreeUtils.getTree(userDepartmentList, userDepartmentMap);
    }

    /**
    * 部门新增，负责人下拉框
    * */
    public List<User> getUserList(){
        return userService.lambdaQuery().eq(User::getStatus, DBConstants.USER_STATUS_NORMAL)
                .eq(User::getApprove, DBConstants.USER_APPROVE_PASS).list();
    }


}
